import java.awt.*;
import java.awt.image.*;

public class ScrollingImage {

	private BufferedImage image;
	private int delta;
	private int topOfImage = 0;
	private double topOfImageDouble = 0;
	private int height;
	
	public ScrollingImage(BufferedImage image, int delta) {
		this.image = image;
		this.delta = delta;
		this.height = image.getHeight(null);
	}
	
	public void update(double elapsedTime) {
		topOfImageDouble += delta * (elapsedTime /1000000000L);
		topOfImageDouble %= height;
		topOfImage = (int)(topOfImageDouble+0.5);
	}
	
	public void draw(Graphics g) {
		if ( topOfImage == 0 ) {
			// the top of the image is at the top of the screen so we only need to draw once
			// draw  destx1, desty1, destx2, desty2, srcx1, srcy1, srcx2, srcy2
	    	g.drawImage(image, 0, 0, 640, 480,
	    					   0, 0, 640, 480, null);
		}
		else if ( topOfImage <= 480) {
			// the top of the image is somewhere in the middle of the screen, lets draw the start of the image 
	    	g.drawImage(image, 0, topOfImage, 640, 480,
	    			           0, 0, 640, 480-topOfImage, null);
	    	
	    	// now lets draw the tail of the image
	    	g.drawImage(image, 0, 0, 640, topOfImage,
	    			           0, height-topOfImage, 640, height, null);
		}
		else {
			// well the top of the image is off the screen, so lets just draw what the screen needs
	    	g.drawImage(image, 0, 0, 640, 480,
	    			           0, height-topOfImage, 640, height-topOfImage+480,null);
		}
    }
}
